import time
from public.settins import Device, Response, Start_Thread, Log_File
import paramiko
from paramiko.ssh_exception import AuthenticationException
from paramiko.channel import Channel

Huawei_screen = 'n\nscreen-length 0 temporary\n'
H3c_screen = 'n\nscreen-length disable\n'
Common_reg = '\n'


def send_screen(d: Device, c: Channel):
    if d.device_type == "huawei":
        c.send(Huawei_screen)
    elif d.device_type == "hp_comware":
        c.send(H3c_screen)


def send_command(d: Device, c: Channel):
    c.send(d.command_string + Common_reg)
    time.sleep(d.read_time)
    out = c.recv(655350)
    if len(out) > 10:
        c.close()
        return handle_recv(d, out)
    else:
        count = 1
        while count <= 3:
            send_command(d, c, )
            count += 1
        c.close()
        return


def handle_recv(d: Device, data: bytes) -> str:
    if d.device_type == "huawei":
        return data.decode("utf-8")
    elif d.device_type == "hp_comware":
        return data.decode("utf-8").replace("\r", "")


def ssh(d: Device):
    try:
        conn = paramiko.SSHClient()
        conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        conn.connect(hostname=d.host, username=d.username, password=d.password, look_for_keys=False)
        c = conn.invoke_shell()
        print(d.host)
        Log_File(Response(d.hostname, d.host, "连接成功").Success)
        send_screen(d, c)
        return True, c
    except AuthenticationException as au:
        Log_File(Response(d.hostname, d.host, "认证失败").Error)
        return False, "认证失败"
    except OSError as o:
        Log_File(Response(d.hostname, d.host, str(o)).Error)
        return False, str(o)
    except Exception as e:
        Log_File(Response(d.hostname, d.host, str(e)).Error)
        return False, str(e)


def run(device: dict) -> Device:
    d = Device(**device)
    status, c = ssh(d)
    if not status:
        d.recv_data = c
        return d
        # return Response_Data(d, data=c)
    d.recv_data = send_command(d, c)
    return d
    # return Response_Data(d, data=out)


if __name__ == '__main__':
    # device_list = api.get_device
    # Start_Thread(run, device_list)
    pass
